package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-08
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private DictListener dictListener;

    @Cacheable(value = "dict")//查询将缓存存入redis，dict::1
    @Override
    public List<Dict> findAllById(Long id) {

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("parent_id",id);

        List<Dict> dicts = dictMapper.selectList(queryWrapper);

        for (Dict dict : dicts) {

            boolean b = selectNext(dict.getId());

            dict.setHasChildren(b);

        }

        return dicts;
    }

    /**
     * 判断是否有下一层子目录
     */
    public boolean selectNext(Long id){

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);

        Integer integer = dictMapper.selectCount(queryWrapper);

        return integer>0;

    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置mime信息
            response.setContentType("application/vnd.ms-excel");
            //设置字符编码
            response.setCharacterEncoding("utf-8");
            //设置头信息，一下载的方式打开
            String fileName = URLEncoder.encode("数据字典", "utf-8");

            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");

            //查询所有的数据
            List<Dict> dicts = dictMapper.selectList(null);
            List<DictEeVo> list = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo dictEeVo = new DictEeVo();

                BeanUtils.copyProperties(dict,dictEeVo);

                list.add(dictEeVo);
            }

            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet().doWrite(list);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @CacheEvict(value = "dict",allEntries = true)//在导入添加的时候，只要是满足dict的缓存，全部清除掉，查询的时候在重新查询生成缓存
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Dict> findChildDataa(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();

        wrapper.eq("parent_id",id);

        List<Dict> list = dictMapper.selectList(wrapper);
        return list;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("dict_code",dictCode);

        Dict dict = dictMapper.selectOne(queryWrapper);

        QueryWrapper<Dict> dictqueryWrapper = new QueryWrapper<>();
        dictqueryWrapper.eq("parent_id",dict.getId());
        List<Dict> dicts = dictMapper.selectList(dictqueryWrapper);
        return dicts;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        if(StringUtils.isEmpty(parentDictCode)){
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",parentDictCode);
            Dict dict = dictMapper.selectOne(wrapper);

            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id",dict.getId());
            dictQueryWrapper.eq("value",value);
            Dict dict1 = dictMapper.selectOne(dictQueryWrapper);
            return dict1.getName();
        }
    }
}
